<?php
/**
 *	[TWCMS] (C)2012 TongWang Inc.
 *	$Id: func.php 2 2013-04-27 07:14:17Z nanown@qq.com $
 */
defined('IN_TWCMS') || exit('Access Denied');

#检测功能目录是否可写
function check_dir_write() {
	$ret = is_dir_write(TWCMS_ROOT);
	echo '<tr><td>'.D.'</td><td>可写 (*nix系统 0777)</td><td>'.($ret ? '<i>可写[√]</i>' : '<u>不可写[×]</u>').'</td></tr>';

	$corename = basename(TWCMS_CORE);
	$dirs = array($corename.D.'data', $corename.D.'plugin', $corename.D.'theme', 'upload');
	foreach($dirs as $dir) {
		$GLOBALS['err_file'] = array();
		$ret = _dir_write(TWCMS_ROOT.D.$dir);
		echo '<tr><td>'.D.$dir.D.'*</td><td>可写 (*nix系统 0777)</td><td>';

		if($ret) {
			echo '<i>可写[√]</i>';
		}else{
			echo '<u>不可写[×]';
			foreach($GLOBALS['err_file'] as $i=>$file) {
				echo '<br>'.str_replace(TWCMS_ROOT, '', $file);
				if($i>8) {
					echo '<br>******'; break;
				}
			}
		}
		echo '</u></td></tr>';
	}
}

#判断填写是否完整
function ajax_check() {
	$_POST = _trim($_POST);
	$_POST['apswd'] = str_replace(' ', '', $_POST['apswd']);

	setcookie("tw_dbhost", $_POST['dbhost']);
	setcookie("tw_dbuser", $_POST['dbuser']);
	setcookie("tw_dbpw", $_POST['dbpw']);
	setcookie("tw_dbname", $_POST['dbname']);
	setcookie("tw_dbpre", $_POST['dbpre']);
	setcookie("tw_test", isset($_POST['test']) ? $_POST['test'] : 0);
	setcookie("tw_founder_name", $_POST['founder_name']);
	setcookie("tw_founder_phone", $_POST['founder_phone']);
	setcookie("tw_founder_mail", $_POST['founder_mail']);
	setcookie("tw_auser", $_POST['auser']);
	setcookie("tw_apswd", $_POST['apswd']);

	$err = 1;
	$name = '';
	if(empty($_POST['dbhost'])) {
		$name = 'dbhost';
		$msg = '数据库主机不能为空';
	}elseif(empty($_POST['dbuser'])) {
		$name = 'dbuser';
		$msg = '数据库用户名不能为空';
	}elseif(empty($_POST['dbname'])) {
		$name = 'dbname';
		$msg = '数据库名不能为空';
	}elseif(empty($_POST['dbpre'])) {
		$name = 'dbpre';
		$msg = '数据库表前辍不能为空';
	}elseif(empty($_POST['auser'])) {
		$name = 'auser';
		$msg = '用户名不能为空';
	}elseif(strlen($_POST['apswd']) < 6) {
		$name = 'apswd';
		$msg = '密码不能小于6位数';
	}elseif(!preg_match("/^[\x7f-\xff]{4,}$/", $_POST['founder_name'])) {
		$name = 'founder_name';
		$msg = '姓名不能少于两个汉字';
	}elseif(!preg_match("/^\d{11}$/", $_POST['founder_phone'])) {
		$name = 'founder_phone';
		$msg = '手机号不正确';
	}elseif(!preg_match("/^[\w\-\.]+@[\w\-][\w\-\.]+\.[a-z]{2,}$/", $_POST['founder_mail'])) {
		$name = 'founder_mail';
		$msg = '邮箱不正确';
	}else{
		$db = new DB;
		$res = @$db->connect($_POST['dbhost'], $_POST['dbuser'], $_POST['dbpw'], $_POST['dbname']);
		if($res == 'error_connect') {
			$name = 'dbpw';
			$msg = '连接MySql失败，数据库用户名和密码是否正确？';
		}elseif($res == 'error_select' && !create_db($db)) {
			$name = 'dbname';
			$msg = '自动创建 '.$_POST['dbname'].' 数据库失败, 请检查是否有权限?';
		}elseif(check_dbpre($db)) {
			$err = 2;
			$msg = '数据库中已经安装过 TwCms, 继续安装将清空全部原有数据, 您确定要继续吗?';
		}else{
			$err = 0;
			$msg = '没有错误';
		}
	}
	exit('{"err":'.$err.', "name":"'.$name.'", "msg":"'.$msg.'"}');
}

#测试连接数据库
function check_db($dbname = 0, $isdbpre=0) {
	$_POST = _trim($_POST);
	$db = new DB;
	if($dbname) {
		$res = @$db->connect($_POST['dbhost'], $_POST['dbuser'], $_POST['dbpw'], $_POST['dbname']);
		$isdbpre && $res=='ok' && check_dbpre($db) && $res = 'exist_dbpre';
	}else{
		$res = @$db->connect($_POST['dbhost'], $_POST['dbuser'], $_POST['dbpw']);
	}

	exit('{"msg":"'.$res.'"}');
}

#检测是否有相同表前辍
function check_dbpre($db) {
	$query = $db->query('SHOW TABLES FROM '.$_POST['dbname']);
	while($row = $db->fetch_row($query)) {
		if(preg_match('#^'.$_POST['dbpre'].'#', $row[0])) return true;
	}
	return false;
}

#尝试创建数据库
function create_db($db) {
	if(!$db->query('CREATE DATABASE `'.$_POST['dbname'].'` DEFAULT CHARACTER SET UTF8')) return false;
	if(!mysql_select_db($_POST['dbname'], $db->link)) return false;
	return true;
}

#清空COOKIE
function ajax_uncookie() {
	setcookie("tw_dbhost", '', time()-1000);
	setcookie("tw_dbuser", '', time()-1000);
	setcookie("tw_dbpw", '', time()-1000);
	setcookie("tw_dbname", '', time()-1000);;
	setcookie("tw_dbpre", '', time()-1000);
	setcookie("tw_founder_name", '', time()-1000);
	setcookie("tw_founder_phone", '', time()-1000);
	setcookie("tw_founder_mail", '', time()-1000);
	setcookie("tw_auser", '', time()-1000);
	setcookie("tw_apswd", '', time()-1000);
	exit('unCookie ok');
}

#安装结束
function install_end() {
	if(empty($_COOKIE['tw_dbhost'])) {
		js_show('获取COOKIE <u>失败</u>');
		return false;
	}

	#连接数据库
	$db = new DB;
	$res = @$db->connect($_COOKIE['tw_dbhost'], $_COOKIE['tw_dbuser'], $_COOKIE['tw_dbpw'], $_COOKIE['tw_dbname'], 'UTF8', 0, $_COOKIE['tw_dbpre']);
	if($res != 'ok') {
		js_show('连接数据库 <u>失败</u>');
		return false;
	}

	#建立表
	$file = TWCMS_CORE.'install'.D.'data'.D.'install.sql';
	if(!file_exists($file)) {
		js_show('install.sql 文件 <u>丢失</u>');
		return false;
	}
	$sqls = split_sql(f_read($file));
	foreach($sqls as $sql) {
		$sql = str_replace("\n", '', trim($sql));
		$ret = $db->query($sql);
		if(substr($sql, 0, 6) == 'CREATE') {
			$name = preg_replace("/CREATE TABLE ([`a-z0-9_]+) .*/is", "\\1", $sql);
			js_show('建立数据表 '.$name.' ... '.is_yes($ret));
		}
		if(!$ret) return false;
	}

	#安装数据
	$file = TWCMS_CORE.'install'.D.'data'.D.'install_data.sql';
	if(!file_exists($file)) {
		js_show('install_data.sql 文件 <u>丢失</u>');
		return false;
	}
	$sqls = split_sql(f_read($file));
	$ret = true;
	foreach($sqls as $sql) {
		$sql = str_replace("\n", '', trim($sql));
		$db->query($sql) || $ret = false;
	}
	js_show('安装数据 ... '.is_yes($ret));
	if(!$ret) return false;

	#安装测试数据
	if(!empty($_COOKIE['tw_test'])) {
		$file = TWCMS_CORE.'install'.D.'data'.D.'install_data_test.sql';
		if(!file_exists($file)) {
			js_show('install_data_test.sql 文件 <u>不存在</u>');
		}else{
			$sqls = split_sql(f_read($file));
			$ret = true;
			foreach($sqls as $sql) {
				$db->query($sql) || $ret = false;
			}
			js_show('安装测试数据 ... '.is_yes($ret));
		}
	}

	#设置创始人
	$apswd = md5($_COOKIE['tw_apswd']);
	$ret = $db->query('INSERT INTO `'.$_COOKIE['tw_dbpre'].'member`(`user`, `password`, `regtime`, `regip`) VALUES ('.S($_COOKIE['tw_auser']).', "'.$apswd.'", '.time().', "'.ip().'")');
	if($ret) {
		$ret = $db->query('INSERT INTO `'.$_COOKIE['tw_dbpre'].'admin` (`user`, `password`, `uid`, `gid`) VALUES ('.S($_COOKIE['tw_auser']).', "'.$apswd.'", '.$db->insert_id().', 1)');
	}
	js_show('设置创始人 ... '.is_yes($ret));
	if(!$ret) return false;

	#设置站点地址
	$webdomain = empty($_SERVER['HTTP_HOST']) ? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST'];
	$webdir = get_webdir();
	$weburl = 'http://'.$webdomain.$webdir;
	$settings = array('webdomain'=>$webdomain, 'webdir'=>$webdir, 'webmail'=>$_COOKIE['tw_founder_mail']);
	$P = base64_encode($_COOKIE['tw_founder_name']).','.base64_encode($_COOKIE['tw_founder_phone']).','.base64_encode($_COOKIE['tw_founder_mail']);
	$ret = set_setting($db, $settings);
	js_show('设置基本信息 ... '.is_yes($ret));
	if(!$ret) return false;

	#设置query数
	$GLOBALS['querynum'] = &$db->querynum;

	#生成配置文件
	$ret = write_config();
	js_show('设置 config.inc.php ... '.is_yes($ret));
	if(!$ret) return false;

	#清空缓存
	$ret = dis_uncache('data'.D.'tplcache');
	if(!$ret) return false;
	$ret = dis_uncache('data'.D.'cache');
	if(!$ret) return false;
	
	#安装结束提示
	end_tips($weburl);

	#清除COOKIE
	echo '<script type="text/javascript">IFR("e","'.$P.'");$.post("?ajax=uncookie");</script>'."\r\n";
	return true;
}

#获取所在目录
function get_webdir() {
	$str = dirname(dirname(dirname($_SERVER['PHP_SELF'])));
	if($str == '\\') return '/';
	if(strlen($str)>1) return $str.'/';
	else return '/';
}

#是否成功
function is_yes($ret) {
	return($ret ? '<i>成功</i>' : '<u>失败</u>');
}

#分割SQL语句
function split_sql($sql) {
	$sql = str_replace('#@_', $_COOKIE['tw_dbpre'], $sql);
	$sql = str_replace("\r", "\n", $sql);
	$ret = array();
	$num = 0;
	$queriesarray = explode(";\n", trim($sql));
	unset($sql);
	foreach($queriesarray as $query) {
		$ret[$num] = isset($ret[$num]) ? $ret[$num] : '';
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			$ret[$num] .= isset($query[0]) && $query[0] == "#" ? NULL : $query;
		}
		$num++;
	}
	return $ret;
}

#设置基本信息
function set_setting($db, $arr) {
	$ret=true;
	foreach($arr as $kay=>$val) {
		if($db->result_first('SELECT id FROM  `'.$_COOKIE['tw_dbpre'].'setting` WHERE kay="'.$kay.'" LIMIT 1')) {
			$db->query('UPDATE `'.$_COOKIE['tw_dbpre'].'setting` SET value='.S($val).' WHERE kay='.S($kay).' LIMIT 1') || $ret=false;
		}else{
			$db->query('INSERT INTO `'.$_COOKIE['tw_dbpre'].'setting`(`kay`,`value`)VALUES('.S($kay).','.S($val).')') || $ret=false;
		}
	}
	return $ret;
}

#安装结束提示
function end_tips($url) {
	$str = '<div class="end"><h3>恭喜！您的网站已安装完成！</h3><p>';
	$str .= '首页地址：<a href="'.$url.'" target="_blank">'.$url.'</a><br>';
	$str .= '管理地址：<a href="'.$url.'admin.php" target="_blank">'.$url.'admin.php</a><br>';
	$str .= '用户名：'.$_COOKIE['tw_auser'].'　<br>密　码：'.$_COOKIE['tw_apswd'].'<br>';
	$str .= '请牢记您以上信息，您可以在登陆后修改登录信息及基本参数。</p></div>';
	js_show($str);
}

#清空缓存目录
function dis_uncache($file) {
	$ret = un_cache(TWCMS_CORE.$file);
	js_show('清空目录 .'.D.basename(TWCMS_CORE).D.$file.' ... '.($ret ? '<i>成功</i>' : '<u>失败</u>'));
	return $ret;
}

#生成config文件
function write_config() {
	$str = "<?php\r\n";
	$str .= "define('TW_DBHOST', '{$_COOKIE['tw_dbhost']}');\r\n";
	$str .= "define('TW_DBUSER', '{$_COOKIE['tw_dbuser']}');\r\n";
	$str .= "define('TW_DBPW', '{$_COOKIE['tw_dbpw']}');\r\n";
	$str .= "define('TW_DBNAME', '{$_COOKIE['tw_dbname']}');\r\n";
	$str .= "define('TW_DBPRE', '{$_COOKIE['tw_dbpre']}');\r\n";
	$str .= "define('TW_DBCHARSET', 'utf8');\r\n";
	$str .= "define('TW_PCONNECT', 0);\r\n\r\n";
	$str .= "define('TW_COOKIEPRE', 'tw".random(6, 2)."');\r\n";
	$str .= "define('TW_KEY', '".random(32, 2)."');\r\n";
	$str .= "define('TW_UPID', 'TW".random(8, 2)."');";
	return f_write(TWCMS_CORE.'data'.D.'config.inc.php', $str);
}

#显示进度
function js_show($str) {
	echo '<script type="text/javascript">jsShow(\''.addslashes($str).'\');</script>'."\r\n";
	flush();
	ob_flush();
}
?>